from datetime import datetime

from app.user import userApi
from module.codes import Codes
from module.users import Users
from flask import request, jsonify, make_response
from utility.encryption import Cryption
from utility.authorization import Authorization

auth = Authorization()
_TIME_FORMAT = '%F %H:%M:%S'


# 登录
@userApi.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        users = Users()
        data = request.get_json()
        username = data['username']
        cryption = Cryption(data['password'])
        password = cryption.encodeMD5()
        tup = users.login(username)
        if len(tup) == 1:
            tup[0]['locked'] = ord(tup[0]['locked'])
            if tup[0]['locked'] == 0:
                if tup[0]['password'] == password:
                    users.update_last_visit_time(username)
                    token = auth.get_token(username)
                    tup[0]['token'] = token
                    tup[0]['userid'] = tup[0]['user_id']
                    tup[0]['create_time'] = datetime.strftime(tup[0]['create_time'], _TIME_FORMAT)
                    return jsonify(tup[0])
                else:
                    return jsonify({'error': '密码错误，请确认后再次尝试！'})
            else:
                return jsonify({'error': '该用户已被锁定！'})
        else:
            return jsonify({'error': '该用户名不存在！'})


# 注册
@userApi.route('/register', methods=['POST'])
def register():
    if request.method == 'POST':
        users = Users()
        data = request.get_json()
        username = data['username']
        cryption = Cryption(data['password'])
        password = cryption.encodeMD5()
        phone = data['phone']
        email = data['email']
        tup = users.login(username)
        if len(tup) == 1:
            return jsonify({'error': '该用户名已存在！'})
        else:
            res = users.register(username, password, username, email, phone)
            if res == 1:
                return jsonify({'success': '注册成功！'})
            else:
                return jsonify({'error': '注册失败！'})


# 用户信息
@userApi.route('/account', methods=['POST', 'DELETE'])
def userinfo():
    token = request.headers['Authorization']
    if auth.vertify_token(token):
        users = Users()
        # 修改信息
        if request.method == 'POST':
            data = request.get_json()
            user_id = data['userid']
            nickname = data['nickname']
            phone = data['phone']
            email = data['email']
            if users.update_userinfo(nickname, phone, email, user_id) == 1:
                return jsonify('修改成功')
            else:
                return jsonify('修改失败')
        # 删除用户
        if request.method == 'DELETE':
            data = request.get_json()
            user_id = data['userId']
            if users.delete_user(user_id) == 1:
                codes = Codes()
                codes.clear_codes(user_id)
                return jsonify('注销成功')
    else:
        return make_response('token失效', 403)


# 修改密码
@userApi.route('/updatePwd', methods=['POST'])
def update_pwd():
    token = request.headers['Authorization']
    if auth.vertify_token(token):
        users = Users()
        if request.method == 'POST':
            data = request.get_json()
            user_id = data['userId']
            cryption = Cryption(data['password'])
            password = cryption.encodeMD5()
            tup = users.get_password(user_id)
            print(password)
            print(tup)
            if tup[0]['password'] == password:
                cryption = Cryption(data['newPwd'])
                newPwd = cryption.encodeMD5()
                if users.update_password(newPwd, user_id) == 1:
                    return jsonify({'success': '修改成功'})
            else:
                return jsonify({'error': '密码错误，请确认后再次尝试！'})
    else:
        return make_response('token失效', 403)
